#include <iostream>
#include <pqxx/pqxx> 
#include <fstream>
#include <sstream>
using namespace std;
using namespace pqxx;

int main(int argc, char* argv[])
{
   ifstream ndvi, lswi, evi;
   ndvi.open("ndvi.txt"); lswi.open("lswi.txt"); evi.open("evi.txt");
   ofstream ndvi2, lswi2, evi2;
   ndvi2.open("ndvi_smoothed.txt"); lswi2.open("lswi_smoothed.txt"); evi2.open("evi_smoothed.txt");

   int x, y, tmp;
   double ndvi_array[46];   double lswi_array[46];   double evi_array[46];
   double ndvi_array2[46];   double lswi_array2[46];   double evi_array2[46];

   // for each line
   for (int line = 1 ; line <= 17930 ; line++){
      // read data from file txt
      ndvi >> x >> y; lswi >> tmp >> tmp; evi >> tmp >> tmp;
      for (int i = 0; i < 46; i++ ){
         ndvi >> ndvi_array[i];
         lswi >> lswi_array[i];
         evi >> evi_array[i];
      }

      // smooth
      // first 2
      for ( int i = 0 ; i < 2; i ++ ){
         ndvi_array2[i] = ndvi_array[i];
         lswi_array2[i] = lswi_array[i];
         evi_array2[i] = evi_array[i];
      }
      // next 42
      for ( int i = 2 ; i < 44; i ++ ){
         int sg_ndvi[5]={ -3, 12, 17, 12, -3 }; int sg_lswi[5]={ -3, 12, 17, 12, -3 }; int sg_evi[5]={ -3, 12, 17, 12, -3 };
         double ndvi_tmp = 0; double lswi_tmp = 0; double evi_tmp = 0;
         for ( int j = -2; j <= 2 ; j++){
            if (ndvi_array[i+j] == 0 ) sg_ndvi[2+j] = 0;
            ndvi_tmp += sg_ndvi[2+j]*ndvi_array[i+j];
            if (lswi_array[i+j] == 0 ) sg_lswi[2+j] = 0;
            lswi_tmp += sg_lswi[2+j]*lswi_array[i+j];
            if (evi_array[i+j] == 0 ) sg_evi[2+j] = 0;
            evi_tmp += sg_evi[2+j]*evi_array[i+j];
         }
         ndvi_array2[i] = ndvi_tmp*1.0 / 35;
         lswi_array2[i] = lswi_tmp*1.0 / 35;
         evi_array2[i] = evi_tmp*1.0 / 35;
      }
      // last 2
      for ( int i = 44 ; i < 46; i ++ ){
         ndvi_array2[i] = ndvi_array[i];
         lswi_array2[i] = lswi_array[i];
         evi_array2[i] = evi_array[i];
      }
      // write to file txt
      ndvi2 << x << " " << y << "\t";      lswi2 << x << " " << y << "\t";      evi2 << x << " " << y << "\t";
      for ( int i = 0 ; i < 46 ; i ++){
         ndvi2 << ndvi_array2[i] << "\t";         lswi2 << lswi_array2[i] << "\t";         evi2 << evi_array2[i] << "\t";
      }
      ndvi2 << endl;      lswi2 << endl;      evi2 << endl;
      cout << line << "/17930" << endl;
   }

   ndvi.close(); lswi.close(); evi.close();
   ndvi2.close(); lswi2.close(); evi2.close();

   cout << "Data is saved in ndvi_smoothed.txt, lswi_smoothed.txt, evi_smoothed.txt" << endl << endl;
   return 0;
}